// import { mergeCart, findCartList } from '@/api/cart'
import {
  mergeCart,
  findCartList,
  insertCart,
  deleteCart,
  updateCart,
  checkAllCart
} from '@/api/cart.js'
// 购物车状态
export default {
  namespaced: true,
  state: () => {
    return {
      showHeaderCart: true,
      list: []
    }
  },
  mutations: {
    // 添加商品到state.list中
    inserCart (state, payload) {
      const goods = state.list.find(it => it.skuId === payload.skuId)
      if (goods) {
        goods.count += payload.count
      } else {
        state.list.push(payload)
      }
    },
    // 修改购物车商品
    updateCart (state, goods) {
      // 1. 找到这个商品
      const obj = state.list.find(it => it.skuId === goods.skuId)
      // 2. 更新状态
      if (obj) {
        for (const p in obj) {
          if (goods[p] !== undefined && goods[p] !== null) {
            obj[p] = goods[p]
          }
        }
      }
    },
    // 删除购物车商品
    deleteCart (state, skuId) {
      const index = state.list.findIndex(item => item.skuId === skuId)
      state.list.splice(index, 1)
    },
    // 修改sku
    updateCartSku (state, { newSku, oldSkuId }) {
      const oldSkuIdx = state.list.findIndex(idx => idx.skuId === oldSkuId)
      if (oldSkuIdx === -1) {
        return
      }
      const oldSkuCopy = { ...state.list[oldSkuIdx] }
      // 解构赋值重命名
      const { oldPrice: price, price: nowPrice, skuId, specsText: attrsText, inventory: stock } = newSku
      // 用新的SKU信息结合老的sku得到一份全新的数据
      const newSkuNew = { ...oldSkuCopy, ...{ price, nowPrice, skuId, attrsText, stock } }
      //  使用splice方法删除旧的sku 并且将全新的数据添加进去
      state.list.splice(oldSkuIdx, 1, newSkuNew)
    },
    // 设置购物车列表
    setCartList (state, list) {
      state.list = list
    }
  },
  actions: {
    inserCart (ctx, goods) {
      return new Promise((resolve, reject) => {
        // 判断是否是登录状态
        if (ctx.rootState.user.profile.token) {
          // 1.调用api，做添加
          insertCart(goods).then(() => {
            // 2.获取最新的购物车数据
            findCartList().then(data => {
              ctx.commit('setCartList', data.result)
              resolve()
            })
          })
        } else { // 未登录状态
          ctx.commit('inserCart', goods)
          resolve()
        }
      })
    },
    // 删除购物车商品
    deleteCart (ctx, skuId) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 登录
          deleteCart([skuId]).then(() => {
            // 2. 取回最新的购物车，保存
            // 获取最新的购物车数据
            findCartList().then(data => {
              ctx.commit('setCartList', data.result)
              resolve()
            })
          })
        } else {
          ctx.commit('deleteCart', skuId)
          resolve()
        }
      })
    },
    // 修改购物车商品
    updateCart (ctx, goods) {
      // goods中必须有skuId,   还有其他修改的属性   selected count
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 登录
          // console.log(ctx, goods)
          updateCart(goods).then(() => {
            findCartList().then(data => {
              ctx.commit('setCartList', data.result)
              resolve()
            })
          })
        } else {
          // 本地数据
          ctx.commit('updateCart', goods)
          // console.log(goods, 1232132)

          resolve()
        }
      })
    },
    // 有效商品的全选与反选
    checkAllCart (ctx, selected) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 登录
          const ids = ctx.getters.validList.map(item => item.skuId)
          checkAllCart({ selected, ids }).then(() => {
            findCartList().then(data => {
              ctx.commit('setCartList', data.result)
              resolve()
            })
          })
        } else {
          ctx.getters.effectiveList.forEach(item => {
            ctx.commit('updateCart', { skuId: item.skuId, selected: selected })
          })
          resolve()
        }
      })
    },
    // 批量删除选中商品   清空无效商品
    batchDeleteCart (ctx, isClearInvalidCart) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 登录
          // 得到需要删除的商品列表（失效，选中）的skuId集合
          const ids = ctx.getters[isClearInvalidCart ? 'invalidList' : 'selectedList'].map(item => item.skuId)
          deleteCart(ids).then(() => {
            findCartList().then((data) => {
              ctx.commit('setCartList', data.result)
              resolve()
            })
          })
        } else { // 没有登录
          // 对于选中的商品列表数据(无效的商品)，循序调用mutations，做删除
          ctx.getters[isClearInvalidCart ? 'invalidList' : 'selectedList'].forEach(it => {
            ctx.commit('deleteCart', it.skuId)
          })

          resolve()
        }
      })
    },
    // 修改规格sku
    updateCartSku (ctx, { oldSkuId, newSku }) {
      return new Promise((resolve, reject) => {
        if (ctx.rootState.user.profile.token) {
          // 登录
          const oldSku = ctx.state.list.find(it => it.skuId === oldSkuId)
          const count = oldSku.count // 获取数据
          deleteCart([oldSkuId]).then(() => {
            // 添加
            insertCart({ skuId: newSku.skuId, count }).then(() => {
              // 获取最新的购物车
              findCartList().then(data => {
                ctx.commit('setCartList', data.result)
                resolve()
              })
            })
          })
        } else {
          ctx.commit('updateCartSku', { oldSkuId, newSku })
          resolve()
        }
      })
    },
    // 合并本地购物车，获取最新
    async mergeLocalCart (ctx) {
      const cartList = ctx.getters.effectiveList.map(({ skuId, selected, count }) => {
        return { skuId, selected, count }
      })
      await mergeCart(cartList)
      // 获取最新的购物车列表
      const res = await findCartList()
      // 更新vuex
      ctx.commit('setCartList', res.result)
    }
  },
  getters: {
    // 有效商品列表
    effectiveList (state, getters) {
      return state.list.filter(item => item.count <= item.stock && item.isEffective)
    },
    // 有效商品总件数
    allCount (state, getters) {
      // console.log(getters.effectiveList.reduce((p, c) => p + c.count, 0))
      return getters.effectiveList.reduce((p, c) => p + c.count, 0)
    },
    // 有效商品总金额
    allAmount (state, getters) {
      return getters.effectiveList.reduce((p, c) => p + c.nowPrice * c.count, 0)
    },
    // 无效的商品列表
    invalidList (state) {
      return state.list.filter(item => !(item.stock > 0 && item.isEffective))
    },
    // 选中商品列表
    selectedList (state, getters) {
      // console.log(123)
      return getters.effectiveList.filter(item => item.selected)
    },
    // 选中商品数量
    seletcedTotal (state, getters) {
      return getters.selectedList.reduce((p, c) => p + c.count, 0)
    },
    // 选中商品总金额
    selectedAmount (state, getters) {
      return getters.selectedList.reduce((p, c) => p + c.nowPrice * c.count, 0)
    },
    // 是否全选
    isCheckAll (state, getters) {
      return (getters.effectiveList.length === getters.selectedList.length) && (getters.effectiveList.length > 0)
    }
  }
}
